/**
* @namespace
* namespace - Contains all the code items related to using the various Google javascript libraries.
* @Depends ksg.base.ui.js
*/
ksg.google = {
	apiLoaded: false,
	initialized: false,
	loginToken: null,
	
	options: {
		apiVersion: "2.s",
		appId: "ksg-app2",
		baseScope: 'https://www.google.com/m8/feeds',
		autoAuthenticate: true,
		googleJsUrl: "http://www.google.com/jsapi",
		authenticationCheckTimeout: 2000
	},
	
	isAuthenticated: function() {
		return this.loginToken != null;
	},
	
	setupGoogleApi: function(pageOptions) {
		var self = this, options = $.extend(this.options, pageOptions);
		var doItNow = function() {
			var gdataLoaded = function() {
				if(options.services.indexOf("contacts") >= 0)
					self.contactsService = new google.gdata.contacts.ContactsService(options.appId);

				//The need to do a setTimeout is very disturbing to me.  There is a problem where the call
				//to google.accounts.user.login will cause the browser to continue to go between the google authorization
				//page and the page hosting this because there is a cookie setup happening that takes time if we check for 
				//this too early, it wont be set and it will think it needs to authenticate again, causing a redirection cycle.
				var auth = function() {
					self.initialized = true;			
						
					if(options.autoAuthenticate == true)
						self.authenticate();
					ksg.App.bizProcMgr.findAndInitDomBizProcs(false);
				};
				var stime = new Date().getTime();
				var checkLogin = function() {
					var x = google.accounts.user.checkLogin(options.baseScope);
					
					if((x != null && x != "" )|| stime + options.authenticationCheckTimeout < new Date().getTime())
						auth();
					else
						setTimeout(checkLogin, 100);					
				};
				//debugger;
				checkLogin();
			};
			
			google.load("gdata", options.apiVersion,{"callback" : gdataLoaded});
			ksg.google.apiLoaded = true;			
		};
		if(typeof (google) == "undefined")
			ksg.ui.loadScriptUrl(options.googleJsUrl, doItNow);
		else
			doItNow();
	},
	
	authenticate: function() {
		this.loginToken = google.accounts.user.login(this.options.baseScope);
		ksg.App.bizProcMgr.findAndInitDomBizProcs(false);
	}
};

try {
	ksg.App.configMgr.registerConfigPartner(function(options) {
		if(options.google)
			ksg.google.setupGoogleApi(options.google);
	});
}
catch(e) {
}
